package calin.podcast;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Simple podcasts database access helper class. Defines the basic CRUD
 * operations for the calin podcast, and gives the ability to list all podcasts
 * as well as retrieve or modify a specific podcast.
 * 
 * This has been improved from the first version of this tutorial through the
 * addition of better error handling and also using returning a Cursor instead
 * of using a collection of inner classes (which is less scalable and not
 * recommended).
 */
public class CalinDatabaseHelper extends SQLiteOpenHelper {
	private static final String DATABASE_NAME = "calin_podcasts.db";
	public String DB_PATH = "";
	private static final int DATABASE_VERSION = 1;
	private SQLiteDatabase Database;
	private final Context mCtx;

	CalinDatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		this.mCtx = context;
		DB_PATH = getDatabasePath();
		try {
			createDataBase();
		} catch (IOException e) {

			throw new Error("Error creating database");

		}
	}

	public String getDatabasePath() {
		return this.mCtx.getDatabasePath(DATABASE_NAME).getAbsolutePath();
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("DROP TABLE IF EXISTS podcasts");
		onCreate(db);
	}

	/**
	 * Creates a empty database on the system and rewrites it with your own
	 * database.
	 * */
	public void createDataBase() throws IOException {

		boolean dbExist = checkDataBase();

		if (!dbExist) {
			// By calling this method and empty database will be created into
			// the default system path
			// of your application so we are gonna be able to overwrite that
			// database with our database.
			this.getReadableDatabase();

			try {

				copyDataBase();

			} catch (IOException e) {

				throw new Error("Error copying database");

			}
		}

	}

	/**
	 * Check if the database already exist to avoid re-copying the file each
	 * time you open the application.
	 * 
	 * @return true if it exists, false if it doesn't
	 */
	private boolean checkDataBase() {

		SQLiteDatabase checkDB = null;

		try {
			String dbPath = getDatabasePath();
			checkDB = SQLiteDatabase.openDatabase(dbPath, null,
					SQLiteDatabase.OPEN_READONLY);

		} catch (SQLiteException e) {

			// database does't exist yet.

		}

		if (checkDB != null) {

			checkDB.close();

		}

		return checkDB != null ? true : false;
	}

	/**
	 * Copies your database from your local assets-folder to the just created
	 * empty database in the system folder, from where it can be accessed and
	 * handled. This is done by transfering bytestream.
	 * */
	private void copyDataBase() throws IOException {
		try {
			// Open your local db as the input stream
			InputStream myInput = mCtx.getAssets().open(DATABASE_NAME);

			// Path to the just created empty db
			String outFileName = getDatabasePath();
			
			// Open the empty db as the output stream
			OutputStream myOutput = new FileOutputStream(outFileName);

			// transfer bytes from the inputfile to the outputfile
			int size = myInput.available();

			byte[] buffer = new byte[size];
			int length;
			while ((length = myInput.read(buffer)) > 0) {
				myOutput.write(buffer, 0, length);
			}

			// Close the streams
			myOutput.flush();
			myOutput.close();
			myInput.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void openDataBase() throws SQLException {

		// Open the database
		String dbPath = getDatabasePath();
		Database = SQLiteDatabase.openDatabase(dbPath, null,
				SQLiteDatabase.OPEN_READONLY);

	}

	@Override
	public synchronized void close() {

		if (Database != null)
			Database.close();

		super.close();

	}

	@Override
	public void onCreate(SQLiteDatabase db) {

	}
}
